"""
流程:
获取订单 -> 判断余额是否足够 -> 发布订单 -> 批量检查订单
"""
import time
import requests
from BloodSpiderModel.BloodSpiderPrint.blood_spider_print_logger import BloodSpiderPrintLogger

class BSRun:
    def __init__(self):
        self.api_url = "http://127.0.0.1:9001/api/game/wzry/"
        self.server_api_Baseurl = "http://127.0.0.1:9001/api/"
        # 我的余额
        self.balance = 0
        # 打印日志
        self.blood_spider_print_logger = BloodSpiderPrintLogger()
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        }

    # 获取我的余额
    def get_balance(self):
        balance_response = requests.get(self.api_url + "dlwz/GetMyBalance/").json()
        self.balance = balance_response["data"]["data"]["balance"]
        self.blood_spider_print_logger.blood_spider_print_info(f"我的余额: {self.balance}")
        return self.balance

    # 获取订单
    def get_order(self, data_count=10):
        """
        获取订单后判断每一个订单的余额是否在我们的投资范围内,把符合范围的订单返回
        """
        my_balance = float(self.get_balance())
        if my_balance <= 5:
            self.blood_spider_print_logger.blood_spider_print_error(f"余额不足, 无法获取订单")
            return []
        order_list_response = requests.get(self.api_url + "dlt/LevelOrderList/", params={
            "Price_Str": "20_40"
        }).json()
        order_new_list = []
        for order_item in order_list_response["data"]["LevelOrderList"]:
            if order_item["Ensure"] > 10:
                # 保证金大于10元, 我们不考虑
                continue
            if float(order_item["Price"]) <= float(my_balance):
                order_new_list.append(order_item)
                # my_balance 需要减去订单金额
                my_balance -= float(order_item["Price"])
        return order_new_list[0 : data_count]

    # 判断余额是否足够
    def check_balance(self, order_data):
        while True:
            if float(order_data["Price"]) > float(self.balance):
                self.blood_spider_print_logger.blood_spider_print_info(f"余额不足, 订单金额: {order_data['Price']}, 我的余额: {self.balance}")
                # 等待6秒
                time.sleep(6)
                self.get_balance()
            else:
                return True
        
    # 发布订单
    def publish_order(self, order_data: dict) -> bool:
        publish_order_response = requests.get(self.api_url + "dlwz/PublishOrder/", params=order_data).json()
        if publish_order_response["code"] != 0:
            self.blood_spider_print_logger.blood_spider_print_error(f"发布订单失败, 响应: {publish_order_response}")
            return False
        return True    

    # 批量检查订单
    def check_order(self) -> bool:
        """
        获取我们的发布订单(待接手的状态) -> 检查订单是否存在
        存在跳过
        不存在取消
        """
        while True:
            my_order_response = requests.get(self.api_url + "order/list/", params={"status": 1}).json()
            self.blood_spider_print_logger.blood_spider_print_info(f"共获取到 {len(my_order_response['data'])} 个订单")
            for order_item in my_order_response["data"]:
                self.blood_spider_print_logger.blood_spider_print_info(f"检查订单: {order_item['order_source_id']}")
                # 在来源平台中查询订单是否存在
                order_source_response = requests.get(self.api_url + "dlt/SearchOrderExist/", params={"OrderID": order_item["order_source_id"]}).json()
                # self.blood_spider_print_logger.blood_spider_print_info(f"行数78, order_source_response变量返回: {order_source_response}")

                if order_source_response["code"] != 0:
                    # 取消订单
                    cancel_order_response = requests.get(self.api_url + "dlwz/CancelOrder/", params={"OrderID": order_item["posting_platform_id"]}).json()
                    if cancel_order_response["code"] != 0:
                        self.blood_spider_print_logger.blood_spider_print_error(f"取消订单失败, 响应: {cancel_order_response}")

                        continue
                    self.blood_spider_print_logger.blood_spider_print_info(f"取消订单成功: {cancel_order_response}")
                    # 通知状态管理器,余额足够
                    requests.get(self.server_api_Baseurl + "status_manage/dlwz_check_balance_enough/", params={"action": "set", "status": "true"})
                    continue
                self.blood_spider_print_logger.blood_spider_print_info(f"该订单已存在: {order_item['order_source_id']}")
                time.sleep(30)
            if len(my_order_response["data"]) == 0:
                # 如果没有订单，获取到0个订单的话，那就向服务器发送，还有钱
                requests.get(self.server_api_Baseurl + "status_manage/dlwz_check_balance_enough/", params={"action": "set", "status": "true"})
            time.sleep(30)

    # 运行
    def run(self):
        # 定义一个变量，表示当前询问状态管理器的次数，如果超过了10次，说明可能大部分都是在前端取消的，所以直接下一步
        check_balance_enough_count = 1
        while True:
            try:
                if check_balance_enough_count <= 10:
                    check_balance_enough_count += 1
                    # 首先询问状态管理器,余额是否足够
                    check_balance_enough_response = requests.get(self.server_api_Baseurl + "status_manage/dlwz_check_balance_enough/", params={"action": "query"}).json()
                    if check_balance_enough_response["data"] == False:
                        self.blood_spider_print_logger.blood_spider_print_info(f"余额不足, 等待检查程序成功取消订单, 当前次数: {check_balance_enough_count - 1}")
                        time.sleep(10)
                        continue
                else:
                    check_balance_enough_count = 1
                    # 继续下一步, 无需等待状态管理器
                order_list = self.get_order()
                # 如果获取的订单是空数组,说明余额不足,就等待检查程序,当检查程序成功取消一单后就重新开始获取订单、发单
                if len(order_list) == 0:
                    # 通知状态管理器,余额不足
                    requests.get(self.server_api_Baseurl + "status_manage/dlwz_check_balance_enough/", params={"action": "set", "status": "false"})
                    continue
                for order_item in order_list:
                    if self.publish_order(order_item):
                        commissionRate = order_item["Price"] * 0.3
                        posting = order_item["Price"] - commissionRate
                        self.blood_spider_print_logger.blood_spider_print_info(f"发布订单成功: {order_item['Title']} | 接单价格: {order_item['Price']} | 发布订单价格: {posting} | 佣金: {commissionRate}")
                    time.sleep(6)
                time.sleep(10)
            except Exception as e:
                self.blood_spider_print_logger.blood_spider_print_error(f"脚本错误, 响应: {e}")
                time.sleep(3)
            self.blood_spider_print_logger.blood_spider_print_info(f"等待10秒后重新开始")
            time.sleep(10)
    
    # 批量取消订单
    def cancel_order(self) -> bool:
        """
        批量取消订单
        """
        my_order_response = requests.get(self.api_url + "order/list/", params={"status": 1}).json()
        self.blood_spider_print_logger.blood_spider_print_info(f"共获取到 {len(my_order_response['data'])} 个订单")
        for order_item in my_order_response["data"]:
            req = requests.get(self.api_url + "dlwz/CancelOrder/", params={"OrderID": order_item["posting_platform_id"]}).json()
            if req["code"] != 0:
                self.blood_spider_print_logger.blood_spider_print_error(f"取消订单失败, 响应: {req}")
                continue
            self.blood_spider_print_logger.blood_spider_print_info(f"取消订单成功: {req}")
            continue
        return True

    # 菜单程序
    def order_menu(self):
        """
        菜单程序
        """
        while True:
            self.blood_spider_print_logger.blood_spider_print_info("1. 发布订单")
            self.blood_spider_print_logger.blood_spider_print_info("2. 取消订单")
            self.blood_spider_print_logger.blood_spider_print_info("3. 检查订单")
            self.blood_spider_print_logger.blood_spider_print_info("4. 退出程序")
            self.blood_spider_print_logger.blood_spider_print_info("5. 获取发布平台余额")
            menu = input("请输入您的选择: ")
            if menu == "1":
                self.run()
            elif menu == "2":
                self.cancel_order()
            elif menu == "3":
                self.check_order()
            elif menu == "4":
                break
            elif menu == "5":
                self.get_balance()
            else:
                self.blood_spider_print_logger.blood_spider_print_error("您的选择有误, 请重新输入")
        return True
   
if __name__ == "__main__":
    bs_run = BSRun()
    bs_run.order_menu()
